package com.zam.Interceptor;

import com.zam.comment.Constants;
import com.zam.exception.ServiceException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author talent_dog
 * @Date 2024/2/13 14:42
 * @Version 1.0
 * prevent-repetition(防止-重复提交)
 */
public class PRInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public PRInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (stringRedisTemplate.opsForValue().get(requestURI) != null) {
            throw new ServiceException(Constants.CODE_601, "操作过快，请稍后再试!!!");
        }
        stringRedisTemplate.opsForValue().set(requestURI,"1",500, TimeUnit.MILLISECONDS);
        return true;
    }
}
